package com.yupi.springbootinit.es.entity;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.yupi.springbootinit.es.entity.Message;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.dromara.easyes.annotation.HighLight;
import org.dromara.easyes.annotation.IndexField;
import org.dromara.easyes.annotation.IndexId;
import org.dromara.easyes.annotation.IndexName;
import org.dromara.easyes.annotation.rely.FieldType;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@IndexName("message_index")
@Data
public class ChatSession {

    @IndexId
    private String id;

    private String sessionId;

    @IndexField(fieldType = FieldType.KEYWORD)
    private String senderName;

    @IndexField(fieldType = FieldType.KEYWORD)
    private String senderId;

    @IndexField(fieldType = FieldType.TEXT)
    @HighLight(preTag = "<strong>", postTag = "</strong>", numberOfFragments = 15)
    private List<String> messageList;

    @IndexField()
    private Boolean isDeleted;

    @IndexField(fieldType = FieldType.DATE)
    private Date createTime;

    public ChatSession() {
        this.messageList = new ArrayList<>(); // 初始化为一个空列表
    }
    // 将 Map 转换为 ChatSession 对象
    public  ChatSession fromMap(Map<String, Object> sourceMap) {
        ChatSession chatSession = new ChatSession();
        chatSession.setId((String) sourceMap.getOrDefault("id", ""));
        chatSession.setSessionId((String) sourceMap.getOrDefault("sessionId", ""));
        chatSession.setSenderName((String) sourceMap.getOrDefault("senderName", ""));
        chatSession.setSenderId((String) sourceMap.getOrDefault("senderId", ""));
        chatSession.setIsDeleted((Boolean) sourceMap.getOrDefault("isDeleted", false));
        List<Map<String, Object>> messageListMaps = (List<Map<String, Object>>) sourceMap.getOrDefault("messageList", new ArrayList<>());
        List<Message> messages = new ArrayList<>();
        for (Map<String, Object> messageMap : messageListMaps) {
            Message message = Message.fromMap(messageMap);
            messages.add(message);
        }
        //将 Message 对象转换为 JSON 字符串
        List<String> messagesJson = new ArrayList<>();
        for (Message message : messages) {
            messagesJson.add(JSONUtil.toJsonStr(message));
        }
        chatSession.setMessageList(messagesJson);
        return chatSession;
    }
}